import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Course from '@/views/course'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/course'
  },
  // 登录
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login')
  },
  // 页面首次进入查看页，不必懒加载
  {
    path: '/course',
    name: 'course',
    component: Course
  },
  // 学习课程
  {
    path: '/learn',
    name: 'learn',
    meta: {
      requireAuth: true
    },
    component: () => import(/* webpackChunkName: "learn" */ '../views/learn')
  },
  // 用户信息
  {
    path: '/user',
    name: 'user',
    meta: {
      requireAuth: true
    },
    component: () => import(/* webpackChunkName: "user" */ '../views/user')
  },
  // 课程信息
  {
    path: '/course-info/:courseId',
    name: 'course-info',
    component: () =>
      import(/* webpackChunkName: "course-info" */ '../views/course-info'),
    props: true
  },
  // 课程视频
  {
    path: '/lesson-video/:lessonId',
    name: 'lesson-video',
    component: () =>
      import(
        /* webpackChunkName: "lesson-video" */ '../views/course-info/lesson-video'
      ),
    props: true
  },
  // 支付页面
  {
    path: '/pay/:courseId',
    name: 'pay',
    meta: {
      requireAuth: true
    },
    component: () => import(/* webpackChunkName: "pay" */ '../views/pay'),
    props: true
  },
  {
    path: '*',
    name: 'error-page',
    component: () =>
      import(/* webpackChunkName: "error-page" */ '../views/error-page')
  }
]

const router = new VueRouter({
  routes
})
// 登录状态监测
router.beforeEach((to, form, next) => {
  // 判断 to 路由是否需要登录认证
  if (to.matched.some(record => record.meta.requireAuth)) {
    // 检测是否有用户信息
    if (!store.state.user) {
      // 跳转登录页
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
    }
    next()
  } else {
    next()
  }
})
export default router
